// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-11-19

package elastic_plugin

import (
	"context"
	"encoding/json"
	"fmt"
	"gitee.com/go-libs/log/common"
	"gitee.com/go-libs/log/conf"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"io"
	"strings"
	"time"
)

// 输出日志.
type writer struct {
	client  *elasticsearch.Client
	err     error
	indices *indices
	timeout time.Duration
}

// +------------------------------------------------------------------------------+
// | Interface methods                                                            |
// +------------------------------------------------------------------------------+

func (o *writer) Write(formatter common.LoggingFormatter, items []common.Item) (err error) {
	var (
		body   []byte
		ctx, _ = context.WithTimeout(context.Background(), o.timeout)
		data   strings.Builder
		res    *esapi.Response
	)

	// 1. 内部错误.
	//    例如建立 Elasticsearch 连接出错.
	if err = o.err; err != nil {
		return
	}

	// 2. 遍历数据.
	for i, item := range items {
		// 2.1 索引信息.
		//     {
		//         "index": {
		//              "_id": "document-unique-id",
		//              "_index": "log-2024.09.10",
		//              "_type": "_doc",
		//         }
		//     }
		data.Write(o.indices.Generate(item, i))
		data.WriteByte('\n')
		// 2.2 数据信息.
		//     {
		//         "level": "INFO",
		//         "text": "message content",
		//         .
		//         .
		//         .
		//     }
		data.Write(formatter.ToByte(item))
		data.WriteByte('\n')
	}

	// 3. 提交数据.
	if res, err = (&esapi.BulkRequest{
		Body: strings.NewReader(data.String()),
	}).Do(ctx, o.client); err != nil {
		return
	}

	// 4. 关闭数据.
	defer func() {
		if res.Body != nil {
			_ = res.Body.Close()
		}
	}()

	// 5. 读取内容.
	if body, err = io.ReadAll(res.Body); err != nil {
		return
	}

	// 6. 处理错误.
	se := &IndicesError{}
	if json.Unmarshal(body, se) == nil && se.Error != nil {
		err = fmt.Errorf(`%s`, se.Error.Reason)
	}
	return
}

// +------------------------------------------------------------------------------+
// | Access methods                                                               |
// +------------------------------------------------------------------------------+

func (o *writer) init() *writer {
	var cfg = conf.New()

	if cfg.ElasticAdapter.Timeout > 0 {
		o.timeout = time.Duration(cfg.ElasticAdapter.Timeout) * time.Second
	} else {
		o.timeout = time.Second * 5
	}

	o.indices = (&indices{}).init()
	o.client, o.err = elasticsearch.NewClient(elasticsearch.Config{
		Addresses: cfg.ElasticAdapter.Addresses,
		Username:  cfg.ElasticAdapter.Username,
		Password:  cfg.ElasticAdapter.Password,
	})
	return o
}
